package com.orange.common.utils;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * TODO
 *
 * @Author YWF
 * @Date 2025/9/8 22:39
 */

public class HashUtils {

    /**
     * 生成字符串的哈希值
     * @param input 输入字符串
     * @param algorithm 哈希算法（如 "MD5", "SHA-1", "SHA-256" 等）
     * @return 哈希值的十六进制字符串表示
     * @throws NoSuchAlgorithmException 如果算法不存在
     */
    public static String hash(String input, String algorithm) throws NoSuchAlgorithmException {
        if (input == null || input.isEmpty()) {
            throw new IllegalArgumentException("Input string cannot be null or empty");
        }

        MessageDigest digest = MessageDigest.getInstance(algorithm);
        byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));

        // 将字节数组转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : hashBytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }

    /**
     * 检查两个文本内容是否相同
     * @param text1 文本1
     * @param text2 文本2
     * @return 是否相同
     */
    public static boolean isSameContent(String text1, String text2) {
        if (text1 == null || text2 == null) {
            return text1 == text2;
        }
        return md5(text1).equals(md5(text2));
    }


    // 常用算法的快捷方法
    public static String md5(String input){
        try {
            return hash(input, "MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5 hashing failed", e);
        }
    }

    public static String sha1(String input) {
        try {
            return hash(input, "SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1 hashing failed", e);
        }
    }

    public static String sha256(String input) {
        try {
            return hash(input, "SHA-256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-256 hashing failed", e);
        }
    }
}